package deal;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;

public class ExceptionChain {
      private  ClassPool pool;
      private  CtClass pt;
      private  Class ptClass;
      private  String cPath;
      private  String classURLStr, qualifiedName;
      public  ExceptionChain(String path){
            this.pool = ClassPool.getDefault();
            this.pt = null;
            this.cPath = null;
            //CtMethod m = null;
             try {
                   pt = pool.get(path);
                   // Construct the directory of the target class.
                   classURLStr = pt.getURL().getPath();
                   qualifiedName = pt.getName();
                   qualifiedName = "/" + qualifiedName.replace('.', '/') + 
                               ".class";
                   if (classURLStr.endsWith(qualifiedName)) {
                         cPath = classURLStr.substring(0, 
                                     classURLStr.indexOf(qualifiedName));
                         ptClass = pt.toClass();
                   }
                   else{
                         throw new Exception("Invalid path for class.");
                   }
                   //m = CtNewMethod.make("public int sayHello() {  System.out.println(\"hello\"); return 0;}", pt);
                   //pt.addMethod(m);
                   // Write class file to its directory.
                   //pt.writeFile(cPath);
                   //this.cPath = cPath;
            } catch (Exception e) {
                   e.printStackTrace();
             }
             pt.defrost();
      }
      public static void main(String[] args){
            ExceptionChain EC = new ExceptionChain("targetSource.souce1");
            CtMethod[] methods = EC.pt.getDeclaredMethods();
            for(int i = 0; i < methods.length; i++){
                  System.out.println(methods[i].getName());
                  CtClass[] exceptionTypes =null;
                  try {
                      
                        exceptionTypes = methods[i].getExceptionTypes();
                  } catch (NotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                  }
                  if(exceptionTypes == null){
                        System.out.println("no exception type in method: "+methods[i].getName());
                  }
                  else{
                        for(int j =0; j < exceptionTypes.length; j++){
                              System.out.println("exception type: "+exceptionTypes[j].getName());
                              
                        }
                  }
            }
            
      }
}
